package cn.edu.stu.interception;

import cn.edu.stu.tool.JWTUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author Karl
 * @Date 2022/12/26 - 1:52
 */
public class BgInterception implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    String token = cookie.getValue();
                    if (token == null) {
                        myForward("请先登录！",request,response);
                        return false;
                    }
                    Map<String,String> map = null;
                    try {
                        map = JWTUtil.verify(token);
                    } catch (TokenExpiredException e) {
                        myForward("token已过期，请重新登录！",request,response);
                        return false;
                    }catch (Exception e){
                        myForward("token错误！",request,response);
                        return false;
                    }
                    //将他的个人信息存到请求对象的属性域中
                    try {
                        request.setAttribute("username",map.get("username"));
                        request.setAttribute("userid",Long.parseLong(map.get("userid")));
                    } catch (Exception e) {
                        myForward("请先登录！！",request,response);
                        return false;
                    }

                    return true;
                }
            }
        }
        myForward("请先登录！！",request,response);
        return false;
    }


    private void myForward(String msg, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("/bg/login").forward(request, response);
    }
}
